<?php

// 本类由系统自动生成，仅供测试用途
class ClientAction extends Action
{
    public function index()
    {
        $this->display();
    }

    public function manage()
    {
        $db = M("version");
        $this->version = $db->where(" package='%s'", array("com.ring"))->find();
        $this->display();
    }

    public function uploadVersion()
    {
        $package = I("package", "");
        $name = I("name", "");
        $verCode = I("verCode", "");
        $feature=I("feature","");
        $size = I("size", 200000000);
        if (isNotBlankString($package) && isNotBlankString($name) && isNotBlankString($verCode)) {
            //进一步校验展示不做
//            import("ORG.Net.UploadFile");
//            $upload = new UploadFile(); // 实例化上传类
//            $upload->maxSize = $size; // 设置附件上传大小
//            $upload->allowExts = array('apk');
//            $upload->savePath = './Public/Uploads/';
//            if (!$upload->upload()) { // 上传错误提示错误信息
//            } else { // 上传成功获取上传文件信息
//                $info = $upload->getUploadFileInfo();
//                $music = M("version");
//                $m["name"] = $name;
//                $m["verCode"] = $verCode;
//                $m["varPath"]= C("httpPath") . "Public/Uploads/" . $info[0]["savename"];
//                $m["feature"] = $feature;
//                $id = $music->where(" package='%s' ",$package)->save($m);
//            }
            //进一步校验展示不做
            $domain = "";
            $upload = new SaeStorage();
            $name = $_FILES["Filedata"]["name"];
            $basename = pathinfo($name, PATHINFO_EXTENSION);
            $tmp_name = $_FILES['Filedata']['tmp_name'];
            $filename = date('YmdHis') . "_" . rand(100, 999) . '.' . $basename;   //获取随机文件名
            $attr = array();
            $s = $upload->upload($domain, $filename, $tmp_name, -1, $attr, false);
            if ($s) {
                $music = M("version");
                $m["name"] = $name;
                $m["verCode"] = $verCode;
                $m["varPath"]=  $s;
                $m["feature"] = $feature;
                $id = $music->where(" package='%s' ",$package)->save($m);
            }
        }
        $db = M("version");
        $this->version = $db->where(" package='%s'", array("com.ring"))->find();
        $this->display("manage");
    }

    /***
     * 客户端注册登陆接口
     */
    public function login()
    {
        $json["success"] = true;
        $mobi = I("mobi", "");
        $imei = I("imei", "");
        $mac = I("imei", $imei);
        if (isMobi($mobi) && ("" != $mac)) {
            $db = M("client_user");
            $client = $db->where(" mobi='%s' and imei='%s' ", array($mobi, $imei))->select();
//            p($client);
            if (count($client) > 0) {
                $id = $client[0]["id"];
//                echo "<br> 主键：".$id;
                $t = date('Y-m-d H:i:s', time());
                $db->updateTime = $t;
                $db->where('id=%d', $id)->setField('updateTime', $t);
                $json["message"] = "登陆成功";
            } else {
                $db->createTime = date('Y-m-d H:i:s', time());//暂时
                $db->mobi = $mobi;
                $db->imei = $imei;
                $db->jiefen = 10;
                $db->add();
                $json["message"] = "第一次登陆，注册成功";
            }
            $token = encode($mobi, $mac);
            $json["token"] = $token;
            // $d=decode($token,$mac);
        } else {
            $json["success"] = false;
            $json["message"] = "传入参数不合法";
            $json["token"] = "";
        }
        outJson($json);
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        $mac = I("mac", "");
        $token = I("token", "");
        $size = I("size", 200000000);
        if (isNotBlankString($token)) {
            $mobi = decode($token, $mac);
            if (isNotBlankString($mobi)) {
                //进一步校验展示不做
                import("ORG.Net.UploadFile");
                $upload = new UploadFile(); // 实例化上传类
                $upload->maxSize = $size; // 设置附件上传大小
                $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg', 'wma', 'mmf', 'mp3', 'mid');
                $upload->savePath = './Public/Uploads/';
                if (!$upload->upload()) { // 上传错误提示错误信息
                    $json["success"] = false;
                    $json["message"] = $upload->getErrorMsg();
                    outJson($json);
                    die;
                } else { // 上传成功获取上传文件信息
                    $info = $upload->getUploadFileInfo();
                    $music = M("music");
                    $music->sname = $info[0]["name"];
                    $music->uuid = $info[0]["savename"];
                    $music->url = C("httpPath") . "Public/Uploads/" . $info[0]["savename"];
                    $music->author = $mobi;
                    $id = $music->add();


                    $json["success"] = true;
                    $json["message"] = "成功";
                    $json["id"] = $id;//文件id
                    $json["url"] = C("httpPath") . "Public/Uploads/" . $info[0]["savename"];
                    outJson($json);
                    die;
                }
            } else {
                outError("token 校验失败");
                die;
            }
        } else {
            outError("token 不能为空");
            die;
        }
    }

    /**
     * 上传文件
     */
    public function saeUpload()
    {
        $mac = I("mac", "");
        $token = I("token", "");
        $size = I("size", 200000000);
        if (isNotBlankString($token)) {
            $mobi = decode($token, $mac);
            if (isNotBlankString($mobi)) {
                //进一步校验展示不做
                $domain = "";
                $upload = new SaeStorage();
                $name = $_FILES["Filedata"]["name"];
                $basename = pathinfo($name, PATHINFO_EXTENSION);
                $tmp_name = $_FILES['Filedata']['tmp_name'];
                $filename = date('YmdHis') . "_" . rand(100, 999) . '.' . $basename;   //获取随机文件名
                $attr = array();
                $s = $upload->upload($domain, $filename, $tmp_name, -1, $attr, false);
                if ($s) {
                    $music = M("music");
                    $music->sname = $name;;
                    $music->uuid = $filename;
                    $music->url = $s;
                    $music->author = $mobi;
                    $id = $music->add();
                    $json["success"] = true;
                    $json["message"] = "成功";
                    $json["id"] = $id;//文件id
                    $json["url"] = $s;
                    outJson($json);
                    die;
                } else {
                    $json["success"] = false;
                    $json["message"] = "上传失败";
                    outJson($json);
                    die;
                }
            } else {
                outError("token校验失败");
                die;
            }
        } else {
            outError("token不能为空");
            die;
        }
    }


    /**
     * 查询新版本
     */
    public function queryNewVersion()
    {
        $db = M("version");
        $client = $db->where(" package='%s'", array("com.ring"))->select();
        if (count($client) > 0) {
            $result = $client[0];
            $result["success"] = true;
            outJson($result);
        } else {
            outError("没有版本信息");
        }
    }


    /***
     * 保存彩铃信息
     */
    public function saveRing()
    {
        $id = I("id", 0);
        $imageId = I("imageId");
        $musicId = I("musicId", 0);
        $jifen = I("jifen", 0);
        $mac = I("mac", "");
        $token = I("token", "");
        if (isNotBlankString($token)) {
            $mobi = decode($token, $mac);
            if (isNotBlankString($mobi)) {
                if ($musicId > 0) {
                    $ring = M("ring");
                    $data["imageId"] = $imageId;
                    $data["musicId"] = $musicId;
                    $data["jifen"] = $jifen;
                    $data["author"] = $mobi;
                    if (0 == $id) {
                        $data["sort"] = 0;
                        $data["createTime"] = date('Y-m-d H:i:s', time());
                        $ring->add($data);
                    } else {
                        $data["imageId"] = $imageId;
                        $data["musicId"] = $musicId;
                        $data["jifen"] = $jifen;
                        $data["author"] = $mobi;
                        $ring->where(" id=%d", $id)->data($data)->save();
                    }
                    outSuccess("添加成功");
                } else {
                    outError("铃声音乐缺失");
                }
            } else {
                outError("token校验失败");
            }
        } else {
            outError("token不能为空");
        }
    }

    /**
     * 分页查询
     */
    public function queryRingPage()
    {
        $mac = I("mac", "");
        $token = I("token", "");
        $type = I("type", "");
        $currentId = I("currentId", 0);
        $pageSize = I("pageSize", 10);
        if (isNotBlankString($token)) {
            $mobi = decode($token, $mac);
            if (isMobi($mobi)) {
                $Model = new Model();
                $sql = "SELECT r.id, r.musicId,r.imageId,m.url as musicUrl,img.url as imageUrl   FROM wx_ring r LEFT JOIN wx_music m on m.id=r.musicId LEFT JOIN wx_music img on img.id=r.musicId where 1=1 ";
                $sql2 = "SELECT COUNT(*) as total  FROM wx_ring r LEFT JOIN wx_music m on m.id=r.musicId LEFT JOIN wx_music img on img.id=r.musicId where 1=1 ";
                if ($currentId > 0) {
                    $sql = $sql . " and r.id<" . $currentId;
                    //      $sql2 = $sql2 . " and r.id<" . $currentId;
                }
                if ("1" == $type) {//官方推荐
                    $sql = $sql . " and (r.author is null or r.author='') ";
                    $sql2 = $sql2 . " and (r.author is null or r.author='') ";
                } elseif ("2" == $type) {
                    $sql = $sql . " and r.author='" . $mobi . "' ";
                    $sql2 = $sql2 . " and r.author='" . $mobi . "' ";
                }
                $sql = $sql . " ORDER BY r.id DESC limit " . $pageSize;
                $row = $Model->query($sql);
                if (is_array($row) && count($row) > 0) {
                    $length = count($row);
                    $c = $row[$length - 1];
                    $json["success"] = true;
                    $json["currentId"] = $c["id"];
                    $json["result"] = $row;

                    $count = $Model->query($sql2);
                    if (count($count) > 0) {
                        $json["totalSize"] = $count[0]["total"];
                    }
                    $json["hasNext"] = false;
                    if ($c["id"] > 0) {
                        $sql3 = "SELECT COUNT(*) as total  FROM wx_ring r LEFT JOIN wx_music m on m.id=r.musicId LEFT JOIN wx_music img on img.id=r.musicId where 1=1 ";
                        if ($c["id"] > 0) {
                            $sql3 = $sql3 . " and r.id<" . $c["id"];
                        }
                        if ("1" == $type) {//官方推荐
                            $sql3 = $sql3 . " and (r.author is null or r.author='') ";
                        } elseif ("2" == $type) {
                            $sql3 = $sql3 . " and r.author='" . $mobi . "' ";
                        }
                        $nextCount = $Model->query($sql3);
                        if (count($nextCount) > 0) {
                            if ($nextCount[0]["total"] > 0) {
                                $json["hasNext"] = true;
                            }
                        }
                    }
                    outJson($json);
                    die;
                } else {
                    $json["success"] = false;
                    $json["message"] = "未查询到数据";
                    outJson($json);
                    die;
                }
            } else {
                outError("token校验失败");
            }
        } else {
            outError("token不能为空");
        }
    }

    /**
     * 分页查询
     */
    public function queryMusicPage()
    {
        $mac = I("mac", "");
        $token = I("token", "ccc");
        $type = I("type", "");
        $currentId = I("currentId", 0);
        $pageSize = I("pageSize", 10);
        $mobi = decode($token, $mac);
        if (isMobi($mobi)) {
            if (isNotBlankString($token)) {
                $Model = new Model();
                $sql = "SELECT  m.id,m.sname,m.url,m.uuid,m.author from wx_music m where 1=1 ";
                $sql2 = "SELECT COUNT(*) as total  from wx_music m  where 1=1 ";
                if ($currentId > 0) {
                    $sql = $sql . " and m.id<" . $currentId;
                    //   $sql2 = $sql2 . " and m.id<" . $currentId;
                }
                if ("1" == $type) {//官方推荐
                    $sql = $sql . " and (m.author is null or m.author='') ";
                    $sql2 = $sql2 . " and (m.author is null or m.author='') ";
                } elseif ("2" == $type) {
                    $sql = $sql . " and m.author='" . $mobi . "' ";
                    $sql2 = $sql2 . " and m.author='" . $mobi . "' ";
                }
                $sql = $sql . " ORDER BY m.id DESC limit " . $pageSize;

//                echo $sql."<br/>";
                $row = $Model->query($sql);
                if (is_array($row) && count($row) > 0) {
                    $length = count($row);
                    $c = $row[$length - 1];
                    $json["success"] = true;
                    $json["currentId"] = $c["id"];
                    $json["result"] = $row;

                    $count = $Model->query($sql2);
                    if (count($count) > 0) {
                        $json["totalSize"] = $count[0]["total"];
                    }
                    $json["hasNext"] = false;
                    if ($c["id"] > 0) {
                        $sql3 = "SELECT COUNT(*)  as total  from wx_music m where 1=1 ";
                        if ($c["id"] > 0) {
                            $sql3 = $sql3 . " and m.id<" . $c["id"];
                        }
                        if ("1" == $type) {//官方推荐
                            $sql3 = $sql3 . " and (m.author is null or m.author='') ";
                        } elseif ("2" == $type) {
                            $sql3 = $sql3 . " and m.author='" . $mobi . "' ";
                        }
                        $nextCount = $Model->query($sql3);
                        if (count($nextCount) > 0) {
                            if ($nextCount[0]["total"] > 0) {
                                $json["hasNext"] = true;
                            }
                        }
                    }
                    outJson($json);
                    die;
                } else {
                    $json["success"] = false;
                    $json["message"] = "未查询到数据";
                    outJson($json);
                    die;
                }
            } else {
                outError("token校验失败");
            }
        } else {
            outError("token不能为空");
        }
    }

    /**
     * 设置对方铃声
     */
    public function saveOrUpdateRing()
    {
        $objMobi = I("objMobi");
        //如果传递$ringId
        $ringId = I("ringId", 0);
        $musicId = I("musicId", 0);
        $musicurl = I("musicurl", "");

        $mac = I("mac", "");
        $token = I("token", "");
        if (!isMobi($objMobi)) {
            outError("对方手机号码有误");
            die;
        }
        if (isNotBlankString($token)) {
            $mobi = decode($token, $mac);
            if (isMobi($mobi)) {
                if ($ringId > 0) {
                    $Model = new Model();
                    $sql = "SELECT r.id, r.musicId,r.imageId,m.url as musicUrl,img.url as imageUrl   FROM wx_ring r LEFT JOIN wx_music m on m.id=r.musicId LEFT JOIN wx_music img on img.id=r.musicId where r.id= " . $ringId;
                    $row = $Model->query($sql);
                    if (count($row) > 0) {
                        $url = $row[0]["musicUrl"];
                        $relation = M("ring_relation");
                        $result = $relation->where(" mobi='%s' and objMobi='%s' ", array($mobi, $objMobi))->select();
                        if (count($result) > 0) {
                            $id = $result[0]["id"];
                            $data["url"] = $url;
                            $data["ringId"] = $ringId;
                            $data["status"] = 0;
                            $data["updateTime"] = date('Y-m-d H:i:s', time());
                            $relation->where('id=%d', $id)->save($data);
                            outSuccess("更新设置成功");
                            die;
                        } else {
                            $data["mobi"] = $mobi;
                            $data["objMobi"] = $objMobi;
                            $data["url"] = $url;
                            $data["status"] = 0;
                            $data["ringId"] = $ringId;
                            $data["createTime"] = date('Y-m-d H:i:s', time());
                            $relation->add($data);
                            outSuccess("新增设置成功");
                            die;
                        }
                    } else {
                        outError("该铃声已经下架");
                        die;
                    }
                } else if ($musicId > 0) {//直接设置音乐
                    $m = M("music");
                    $row = $m->where(" id=%d", $musicId)->select();
                    if (count($row) > 0) {
                        $url = $row[0]["url"];
                        $relation = M("ring_relation");
                        $result = $relation->where(" mobi='%s' and objMobi='%s' ", array($mobi, $objMobi))->select();
                        if (count($result) > 0) {
                            $id = $result[0]["id"];
                            $data["url"] = $url;
                            $data["status"] = 0;
                            $data["musicId"] = $musicId;
                            $data["updateTime"] = date('Y-m-d H:i:s', time());
                            $relation->where('id=%d', $id)->save($data);
                            outSuccess("重新设置成功");
                            die;
                        } else {
                            $data["mobi"] = $mobi;
                            $data["objMobi"] = $objMobi;
                            $data["url"] = $url;
                            $data["status"] = 0;
                            $data["musicId"] = $musicId;
                            $data["createTime"] = date('Y-m-d H:i:s', time());
                            $relation->add($data);
                            outSuccess("设置铃声成功");
                            die;
                        }
                    } else {
                        outError("该铃声已经下架");
                        die;
                    }
                } else if ("" != $musicurl) {
                    $url = $musicurl;
                    $relation = M("ring_relation");
                    $result = $relation->where(" mobi='%s' and objMobi='%s' ", array($mobi, $objMobi))->select();
                    if (count($result) > 0) {
                        $id = $result[0]["id"];
                        $data["url"] = $url;
                        $data["status"] = 0;
                        $data["updateTime"] = date('Y-m-d H:i:s', time());
                        $relation->where('id=%d', $id)->save($data);
                        outSuccess("重新设置成功");
                        die;
                    } else {
                        $data["mobi"] = $mobi;
                        $data["objMobi"] = $objMobi;
                        $data["url"] = $url;
                        $data["createTime"] = date('Y-m-d H:i:s', time());
                        $relation->add($data);
                        outSuccess("设置铃声成功");
                        die;
                    }
                } else {
                    outError("ERROR未设置铃声");
                }
            } else {
                outError("token校验失败");
            }
        } else {
            outError("token不能为空");
        }
    }


    /**
     * 查询别人给我设置的铃声
     */
    public function queryMyRings()
    {
        $mac = I("mac", "");
        $token = I("token", "");
        if (isNotBlankString($token)) {
            $mobi = decode($token, $mac);
            if (isMobi($mobi)) {
                $relation = M("ring_relation");
                $result = $relation->where("  objMobi='%s' and status=%d ", array($mobi, 0))->select();//查询要更新de结果
                $json["count"] = count($result);//需要更新条数
                $json["result"] = $result;
                $json["success"] = true;
                $json["message"] = "查询成功";
                outJson($json);
            } else {
                outError("token校验失败");
            }
        } else {
            outError("token不能为空");
        }
    }

    /**
     * 设置更新结果反馈
     */
    public function updateReback()
    {
        $id = I("id", 0);
        $mac = I("mac", "");
        $token = I("token", "");
        if (isNotBlankString($token)) {
            $mobi = decode($token, $mac);
            if (isMobi($mobi)) {
                if ($id > 0) {
                    $relation = M("ring_relation");
                    $result = $relation->where('id=%d', $id)->setField('status', 1);
                    if ($result > 0) {
                        outSuccess("成功" . $result . "条记录");
                    } else {
                        outError("传入关系id" . $id . "作用0条记录");
                    }
                } else {
                    outError("没有传入关系id");
                }
            } else {
                outError("token校验失败");
            }
        } else {
            outError("token不能为空");
        }
    }
}